package org.oschina.api.user.role.service;

import java.util.ArrayList;
import java.util.List;
import org.oschina.Constants;
import org.oschina.Message;
import org.oschina.Module;
import org.oschina.ResultUtil;
import org.oschina.api.BaseService;
import org.oschina.api.manage.module.service.ModuleService;
import org.oschina.api.manage.module.vo.ModuleVo;
import org.oschina.api.user.role.dao.UserRoleDAO;
import org.oschina.api.user.role.model.UserRole;
import org.oschina.api.user.role.vo.UserRoleVo;
import org.oschina.api.user.user.model.User;
import org.oschina.bean.Result;
import org.oschina.security.annotation.Require;
import org.oschina.api.index.service.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserRoleService extends BaseService {

	@Autowired
	private UserRoleDAO roleDAO;
	@Autowired
	private IndexService indexService;
	@Autowired
	private ModuleService moduleService;
	
	/**
	 * 根据角色和类型返回
	 * @param role
	 * @param type
	 * @return
	 */
	@Require(authorization=Module.MODULE_2)
	public List<ModuleVo> findVoByRoleAndType(int role,int type)
	{
		return _findVoByRoleAndType(role, type);
	}
	
	/**
	 * 更新角色模块
	 * @param role
	 * @param modules
	 * @return
	 */
	@Require(authorization=Module.MODULE_2)
	public Result updateModuleByRole(int role,int type,int modules[])
	{
		List<UserRole> roles=new ArrayList<UserRole>();
		for(int module:modules)
		{
			ModuleVo moduleVo=moduleService._findVoById(module);
			if(moduleVo==null || !moduleVo.getType().equals(type))
				return ResultUtil.getFailure(Message.ERROR_DATA_ERROR);
			
			UserRole temp=new UserRole();
			temp.setId(_getIndex());
			temp.setRole(role);
			temp.setModule(module);
			roles.add(temp);
		}
		
		roleDAO.updateModuleByRole(role, type,roles);
		
		return ResultUtil.getSuccess(Message.ROLE_UPDATE_SUCCESS);
	}
	
	/**
	 * 根据角色和模块返回
	 * @param role
	 * @param module
	 * @return
	 */
	public UserRoleVo _findVoByRoleAndModule(User user,int module)
	{
		return roleDAO.findVoByRoleAndModule(user.getRole(), module);
	}
	
	/**
	 * 根据角色和类型返回
	 * @param role
	 * @param type
	 * @return
	 */
	public List<ModuleVo> _findVoByRoleAndType(User user,int type)
	{
		return _findVoByRoleAndType(user.getRole(), type);
	}
	
	/**
	 * 根据角色和类型返回
	 * @param role
	 * @param type
	 * @return
	 */
	private List<ModuleVo> _findVoByRoleAndType(int role,int type)
	{
		return roleDAO.findVoByRoleAndType(role, type);
	}
	
	private int _getIndex()
	{
		return indexService.getMajorById(Constants.INDEX_USER_ROLE);
	}
}